#include <iostream>
#include <functional>

using std::cout;
using std::endl;
using std::bind;
using std::function;

int add(int x, int y)
{
    cout << "int add(int, int)" << endl;
    return x + y;
}

int multiply(int x, int y, int z)
{
    cout << "int multiply(int, int, int)" << endl;
    return x * y * z;
}

class Example
{
public:
    int add(int x, int y)
    {
        cout << "int Example::add(int, int)" << endl;
        return x + y;
    }

    int data = 100;//C++11的用法
};

void test()
{
    //函数的形态（类型、标签）:函数的返回类型 + 函数的参数列表（参数的
    //个数、顺序、类型）
    //add函数的形态:int(int, int)
    //f的形态:int()
    /* auto f = bind(&add, 1, 2); */
    function<int()> f = bind(&add, 1, 2);
    cout << "f() = " << f() << endl;

    cout << endl;
    //multiply函数的形态:int(int, int, int)
    //f2的形态:int()
    function<int()> f2 = bind(&multiply, 3, 4, 5);
    cout << "f2() = " << f2() << endl;

    cout << endl;
    Example ex;
    //add的函数形态：int(Example *, int, int)
    //f3的形态:int()
    function<int()> f3 = bind(&Example::add, &ex, 10, 20);
    cout << "f3() = " << f3() << endl;

    cout << endl;
    //占位符
    /* auto f4 = bind(add, 100,  std::placeholders::_1); */
    using namespace std::placeholders;
    //add函数的形态:int(int, int)
    //f4的形态:int(int)
    function<int(int)> f4 = bind(add, 100, _1);
    cout << "f4(300) = " << f4(300) << endl;

    cout << endl << endl;
    function<int(int, int)> f5 = bind(add, _1, _2);
    cout << "f5(100, 900) = " << f5(100, 900) << endl;

    cout << endl << endl;
    function<int()> f6 = bind(&Example::data, &ex);
    cout << "f6() = " << f6() << endl;
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

